{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# multi_factor\n",
    "\n",
    "## 介绍\n",
    "提供多因子处理和组合功能"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## orthogonalize\n",
    "- ` jaqs_fxdayu.research.signaldigger.multi_factor.orthogonalize(factors_dict=None,standardize_type=\"z_score\",winsorization=False,index_member=None) `\n",
    "\n",
    "**简要描述：**\n",
    "\n",
    "- 因子间存在较强同质性时，使用施密特正交化方法对因子做正交化处理，用得到的正交化残差作为因子\n",
    "\n",
    "**参数:**\n",
    "\n",
    "|字段|必选|类型|说明|\n",
    "|:----    |:---|:----- |-----   |\n",
    "|factors_dict|是|dict of pandas.DataFrame | 若干因子组成的字典(dict),形式为:{\"factor_name_1\":factor_1,\"factor_name_2\":factor_2}。每个因子值格式为一个pd.DataFrame，索引(index)为date,column为asset|\n",
    "|standardize_type|否|string| 标准化方法，有\"rank\"（排序标准化）,\"z_score\"(z-score标准化)两种（\"rank\"/\"z_score\"），默认为\"z_score\"|\n",
    "|winsorization|否|bool| 是否对因子执行去极值操作。默认不执行（False）|\n",
    "|index_member |否|pandas.DataFrame of bool |是否是指数成分股。日期为索引,证券品种为columns的二维bool值表格,True代表该品种在该日期下属于指数成分股。传入该参数,则在对因子进行标准化/去极值操作时所纳入的样本只有每期横截面上属于对应指数成分股的股票，默认为空|\n",
    "\n",
    "\n",
    "**返回:**\n",
    "\n",
    "正交化处理后所得的一系列新因子。dict of pandas.DataFrame\n",
    "\n",
    "**示例：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataview loaded successfully.\n"
     ]
    }
   ],
   "source": [
    "from jaqs_fxdayu.data import DataView\n",
    "from jaqs_fxdayu.research.signaldigger.multi_factor import orthogonalize\n",
    "\n",
    "# 加载dataview数据集\n",
    "dv = DataView()\n",
    "dataview_folder = './data'\n",
    "dv.load_dataview(dataview_folder)\n",
    "\n",
    "# 正交化\n",
    "factors_dict = {signal:dv.get_ts(signal) for signal in [\"pb\",\"pe\"]}\n",
    "new_factors = orthogonalize(factors_dict=factors_dict,\n",
    "                            standardize_type=\"z_score\",\n",
    "                            winsorization=False,\n",
    "                            index_member=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['pb', 'pe'])\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>symbol</th>\n",
       "      <th>000001.SZ</th>\n",
       "      <th>000002.SZ</th>\n",
       "      <th>000008.SZ</th>\n",
       "      <th>000009.SZ</th>\n",
       "      <th>000027.SZ</th>\n",
       "      <th>000039.SZ</th>\n",
       "      <th>000060.SZ</th>\n",
       "      <th>000061.SZ</th>\n",
       "      <th>000063.SZ</th>\n",
       "      <th>000069.SZ</th>\n",
       "      <th>...</th>\n",
       "      <th>601988.SH</th>\n",
       "      <th>601989.SH</th>\n",
       "      <th>601992.SH</th>\n",
       "      <th>601997.SH</th>\n",
       "      <th>601998.SH</th>\n",
       "      <th>603000.SH</th>\n",
       "      <th>603160.SH</th>\n",
       "      <th>603858.SH</th>\n",
       "      <th>603885.SH</th>\n",
       "      <th>603993.SH</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>trade_date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>20170502</th>\n",
       "      <td>-0.661167</td>\n",
       "      <td>-0.321008</td>\n",
       "      <td>0.137600</td>\n",
       "      <td>0.117712</td>\n",
       "      <td>-0.570730</td>\n",
       "      <td>-0.776328</td>\n",
       "      <td>-0.262312</td>\n",
       "      <td>-0.630645</td>\n",
       "      <td>-0.220092</td>\n",
       "      <td>-0.444949</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.673545</td>\n",
       "      <td>-0.996365</td>\n",
       "      <td>-0.388348</td>\n",
       "      <td>-0.395778</td>\n",
       "      <td>-0.658705</td>\n",
       "      <td>0.429739</td>\n",
       "      <td>3.959548</td>\n",
       "      <td>0.406094</td>\n",
       "      <td>0.197670</td>\n",
       "      <td>0.081429</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170503</th>\n",
       "      <td>-0.657938</td>\n",
       "      <td>-0.326229</td>\n",
       "      <td>0.134788</td>\n",
       "      <td>0.112238</td>\n",
       "      <td>-0.571492</td>\n",
       "      <td>-0.777890</td>\n",
       "      <td>-0.267336</td>\n",
       "      <td>-0.639522</td>\n",
       "      <td>-0.206775</td>\n",
       "      <td>-0.447106</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.671494</td>\n",
       "      <td>-1.002554</td>\n",
       "      <td>-0.425115</td>\n",
       "      <td>-0.389544</td>\n",
       "      <td>-0.657170</td>\n",
       "      <td>0.444861</td>\n",
       "      <td>3.968815</td>\n",
       "      <td>0.413581</td>\n",
       "      <td>0.206661</td>\n",
       "      <td>0.160738</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170504</th>\n",
       "      <td>-0.662247</td>\n",
       "      <td>-0.319974</td>\n",
       "      <td>0.132233</td>\n",
       "      <td>0.112591</td>\n",
       "      <td>-0.570338</td>\n",
       "      <td>-0.779594</td>\n",
       "      <td>-0.277660</td>\n",
       "      <td>-0.641221</td>\n",
       "      <td>-0.204759</td>\n",
       "      <td>-0.444954</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.671135</td>\n",
       "      <td>-1.001230</td>\n",
       "      <td>-0.404384</td>\n",
       "      <td>-0.391661</td>\n",
       "      <td>-0.658434</td>\n",
       "      <td>0.410504</td>\n",
       "      <td>3.948198</td>\n",
       "      <td>0.402080</td>\n",
       "      <td>0.204508</td>\n",
       "      <td>0.137293</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170505</th>\n",
       "      <td>-0.664870</td>\n",
       "      <td>-0.319372</td>\n",
       "      <td>0.097919</td>\n",
       "      <td>0.090680</td>\n",
       "      <td>-0.571798</td>\n",
       "      <td>-0.782509</td>\n",
       "      <td>-0.275168</td>\n",
       "      <td>-0.636404</td>\n",
       "      <td>-0.208189</td>\n",
       "      <td>-0.448794</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.670085</td>\n",
       "      <td>-0.997497</td>\n",
       "      <td>-0.409683</td>\n",
       "      <td>-0.401536</td>\n",
       "      <td>-0.659185</td>\n",
       "      <td>0.395936</td>\n",
       "      <td>3.909582</td>\n",
       "      <td>0.397496</td>\n",
       "      <td>0.228932</td>\n",
       "      <td>0.127569</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170508</th>\n",
       "      <td>-0.665537</td>\n",
       "      <td>-0.328892</td>\n",
       "      <td>0.075998</td>\n",
       "      <td>0.078145</td>\n",
       "      <td>-0.576013</td>\n",
       "      <td>-0.777366</td>\n",
       "      <td>-0.263822</td>\n",
       "      <td>-0.619676</td>\n",
       "      <td>-0.227388</td>\n",
       "      <td>-0.448982</td>\n",
       "      <td>...</td>\n",
       "      <td>-0.667077</td>\n",
       "      <td>-0.982399</td>\n",
       "      <td>-0.452894</td>\n",
       "      <td>-0.410854</td>\n",
       "      <td>-0.656776</td>\n",
       "      <td>0.412096</td>\n",
       "      <td>4.041803</td>\n",
       "      <td>0.375715</td>\n",
       "      <td>0.217575</td>\n",
       "      <td>0.144361</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 330 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "symbol      000001.SZ  000002.SZ  000008.SZ  000009.SZ  000027.SZ  000039.SZ  \\\n",
       "trade_date                                                                     \n",
       "20170502    -0.661167  -0.321008   0.137600   0.117712  -0.570730  -0.776328   \n",
       "20170503    -0.657938  -0.326229   0.134788   0.112238  -0.571492  -0.777890   \n",
       "20170504    -0.662247  -0.319974   0.132233   0.112591  -0.570338  -0.779594   \n",
       "20170505    -0.664870  -0.319372   0.097919   0.090680  -0.571798  -0.782509   \n",
       "20170508    -0.665537  -0.328892   0.075998   0.078145  -0.576013  -0.777366   \n",
       "\n",
       "symbol      000060.SZ  000061.SZ  000063.SZ  000069.SZ    ...      601988.SH  \\\n",
       "trade_date                                                ...                  \n",
       "20170502    -0.262312  -0.630645  -0.220092  -0.444949    ...      -0.673545   \n",
       "20170503    -0.267336  -0.639522  -0.206775  -0.447106    ...      -0.671494   \n",
       "20170504    -0.277660  -0.641221  -0.204759  -0.444954    ...      -0.671135   \n",
       "20170505    -0.275168  -0.636404  -0.208189  -0.448794    ...      -0.670085   \n",
       "20170508    -0.263822  -0.619676  -0.227388  -0.448982    ...      -0.667077   \n",
       "\n",
       "symbol      601989.SH  601992.SH  601997.SH  601998.SH  603000.SH  603160.SH  \\\n",
       "trade_date                                                                     \n",
       "20170502    -0.996365  -0.388348  -0.395778  -0.658705   0.429739   3.959548   \n",
       "20170503    -1.002554  -0.425115  -0.389544  -0.657170   0.444861   3.968815   \n",
       "20170504    -1.001230  -0.404384  -0.391661  -0.658434   0.410504   3.948198   \n",
       "20170505    -0.997497  -0.409683  -0.401536  -0.659185   0.395936   3.909582   \n",
       "20170508    -0.982399  -0.452894  -0.410854  -0.656776   0.412096   4.041803   \n",
       "\n",
       "symbol      603858.SH  603885.SH  603993.SH  \n",
       "trade_date                                   \n",
       "20170502     0.406094   0.197670   0.081429  \n",
       "20170503     0.413581   0.206661   0.160738  \n",
       "20170504     0.402080   0.204508   0.137293  \n",
       "20170505     0.397496   0.228932   0.127569  \n",
       "20170508     0.375715   0.217575   0.144361  \n",
       "\n",
       "[5 rows x 330 columns]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(new_factors.keys())\n",
    "new_factors[\"pe\"].head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## get_factors_ic_df\n",
    "- ` jaqs_fxdayu.research.signaldigger.multi_factor.get_factors_ic_df(*args, **kwargs) `\n",
    "\n",
    "**简要描述：**\n",
    "\n",
    "-  获取多个因子ic值序列矩阵\n",
    "\n",
    "**参数:**\n",
    "\n",
    "|字段|必选|类型|说明|\n",
    "|:----    |:---|:----- |-----   |\n",
    "|factors_dict|是|dict of pandas.DataFrame | 若干因子组成的字典(dict),形式为:{\"factor_name_1\":factor_1,\"factor_name_2\":factor_2}。每个因子值格式为一个pd.DataFrame，索引(index)为date,column为asset|\n",
    "|price |是，price与daily_ret二选一  |pandas.DataFrame|因子涉及到的股票的价格数据，用于作为进出场价用于计算收益,日期为索引，股票品种为columns|\n",
    "|daily_ret |是，price与daily_ret二选一  |pandas.DataFrame| 因子涉及到的股票的每日收益，日期为索引，股票品种为columns|\n",
    "|benchmark_price | 否，benchmark_price与daily_benchmark_ret二选一  |pandas.DataFrame or pandas.Series|基准价格，日期为索引。用于计算因子涉及到的股票的持有期**相对收益**--相对基准。默认为空，为空时计算的收益为**绝对收益**。|\n",
    "|daily_benchmark_ret | 否，benchmark_price与daily_benchmark_ret二选一  |pandas.DataFrame or pandas.Series|基准日收益，日期为索引。用于计算因子涉及到的股票的持有期**相对收益**--相对基准。默认为空，为空时计算的收益为**绝对收益**。|\n",
    "|high |否  |pandas.DataFrame|因子涉及到的股票的最高价数据,用于计算持有期潜在最大上涨收益,日期为索引，股票品种为columns,默认为空|\n",
    "|low |否  |pandas.DataFrame|因子涉及到的股票的最低价数据,用于计算持有期潜在最大下跌收益,日期为索引，股票品种为columns,默认为空|\n",
    "|group |否  |pandas.DataFrame|因子涉及到的股票的分组(行业分类),日期为索引，股票品种为columns,默认为空|\n",
    "|period |否  |int|持有周期,默认为5,即持有5天|\n",
    "|n_quantiles |否  |int|根据每日因子值的大小分成n_quantiles组,默认为5,即将因子每天分成5组|\n",
    "|mask |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示在做因子分析时是否要对某期的某个品种过滤。对应位置为True则**过滤**（剔除）——不纳入因子分析考虑。默认为空，不执行过滤操作|\n",
    "|can_enter |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示某期的某个品种是否可以买入(进场)。对应位置为True则可以买入。默认为空，任何时间任何品种均可买入|\n",
    "|can_exit |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示某期的某个品种是否可以卖出(出场)。对应位置为True则可以卖出。默认为空，任何时间任何品种均可卖出|\n",
    "|forward |否  |bool|收益对齐方式,forward=True则在当期因子下对齐下一期实现的收益；forward=False则在当期实现收益下对齐上一期的因子值。默认为True|\n",
    "|commission |否 |float|手续费比例,每次换仓收取的手续费百分比,默认为万分之八0.0008|\n",
    "|ret_type |否 |string|计算何种收益的ic。目前支持的收益类型有return, upside_ret, downside_ret,分别代表固定调仓收益,潜在最大上涨收益,潜在最大下跌收益。默认为return--固定调仓收益|\n",
    "\n",
    "**返回:**\n",
    "\n",
    "ic_df 多个因子ic值序列矩阵\n",
    "类型pd.Dataframe,索引（index）为datetime,columns为各因子名称，与factors_dict中的对应。\n",
    "如：\n",
    "\n",
    "```\n",
    "\n",
    "         BP\t　　　     CFP\t　　　EP\t　　ILLIQUIDITY\tREVS20\t　　SRMI\t　　　VOL20\n",
    "date\n",
    "2016-06-24\t0.165260\t0.002198\t0.085632\t-0.078074\t0.173832\t0.214377\t0.068445\n",
    "2016-06-27\t0.165537\t0.003583\t0.063299\t-0.048674\t0.180890\t0.202724\t0.081748\n",
    "2016-06-28\t0.135215\t0.010403\t0.059038\t-0.034879\t0.111691\t0.122554\t0.042489\n",
    "2016-06-29\t0.068774\t0.019848\t0.058476\t-0.049971\t0.042805\t0.053339\t0.079592\n",
    "2016-06-30\t0.039431\t0.012271\t0.037432\t-0.027272\t0.010902\t0.077293\t-0.050667\n",
    "```\n",
    "\n",
    "\n",
    "\n",
    "**示例：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nan Data Count (should be zero) : 0;  Percentage of effective data: 99%\n",
      "Nan Data Count (should be zero) : 0;  Percentage of effective data: 99%\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>pb</th>\n",
       "      <th>pe</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>trade_date</th>\n",
       "      <th>group</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"5\" valign=\"top\">20170503</th>\n",
       "      <th>交通运输</th>\n",
       "      <td>0.308566</td>\n",
       "      <td>0.052632</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>休闲服务</th>\n",
       "      <td>0.200000</td>\n",
       "      <td>-0.800000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>传媒</th>\n",
       "      <td>0.237878</td>\n",
       "      <td>-0.112633</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>公用事业</th>\n",
       "      <td>0.418182</td>\n",
       "      <td>0.572727</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>农林牧渔</th>\n",
       "      <td>0.314286</td>\n",
       "      <td>-0.600000</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        pb        pe\n",
       "trade_date group                    \n",
       "20170503   交通运输   0.308566  0.052632\n",
       "           休闲服务   0.200000 -0.800000\n",
       "           传媒     0.237878 -0.112633\n",
       "           公用事业   0.418182  0.572727\n",
       "           农林牧渔   0.314286 -0.600000"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from jaqs_fxdayu.research.signaldigger.multi_factor import get_factors_ic_df\n",
    "\n",
    "factor_ic_df = get_factors_ic_df(factors_dict,\n",
    "                                 price=dv.get_ts(\"close_adj\"),\n",
    "                                 high=dv.get_ts(\"high_adj\"), # 可为空\n",
    "                                 low=dv.get_ts(\"low_adj\"),# 可为空\n",
    "                                 group=dv.get_ts(\"sw1\"), # 可为空\n",
    "                                 n_quantiles=5,# quantile分类数\n",
    "                                 period=5,# 持有期\n",
    "                                 benchmark_price=dv.data_benchmark, # 基准价格 可不传入，持有期收益（return）计算为绝对收益\n",
    "                                 commission = 0.0008,\n",
    "                                 ret_type = 'upside_ret' # 计算最大潜在上涨收益的ic \n",
    "                                 )\n",
    "factor_ic_df.dropna(how=\"all\").head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## get_factors_ret_df\n",
    "- ` jaqs_fxdayu.research.signaldigger.multi_factor.get_factors_ret_df(*args, **kwargs) `\n",
    "\n",
    "**简要描述：**\n",
    "\n",
    "-  获取多个因子收益序列矩阵\n",
    "\n",
    "**参数:**\n",
    "\n",
    "|字段|必选|类型|说明|\n",
    "|:----    |:---|:----- |-----   |\n",
    "|factors_dict|是|dict of pandas.DataFrame | 若干因子组成的字典(dict),形式为:{\"factor_name_1\":factor_1,\"factor_name_2\":factor_2}。每个因子值格式为一个pd.DataFrame，索引(index)为date,column为asset|\n",
    "|price |是，price与daily_ret二选一  |pandas.DataFrame|因子涉及到的股票的价格数据，用于作为进出场价用于计算收益,日期为索引，股票品种为columns|\n",
    "|daily_ret |是，price与daily_ret二选一  |pandas.DataFrame| 因子涉及到的股票的每日收益，日期为索引，股票品种为columns|\n",
    "|benchmark_price | 否，benchmark_price与daily_benchmark_ret二选一  |pandas.DataFrame or pandas.Series|基准价格，日期为索引。用于计算因子涉及到的股票的持有期**相对收益**--相对基准。默认为空，为空时计算的收益为**绝对收益**。|\n",
    "|daily_benchmark_ret | 否，benchmark_price与daily_benchmark_ret二选一  |pandas.DataFrame or pandas.Series|基准日收益，日期为索引。用于计算因子涉及到的股票的持有期**相对收益**--相对基准。默认为空，为空时计算的收益为**绝对收益**。|\n",
    "|high |否  |pandas.DataFrame|因子涉及到的股票的最高价数据,用于计算持有期潜在最大上涨收益,日期为索引，股票品种为columns,默认为空|\n",
    "|low |否  |pandas.DataFrame|因子涉及到的股票的最低价数据,用于计算持有期潜在最大下跌收益,日期为索引，股票品种为columns,默认为空|\n",
    "|group |否  |pandas.DataFrame|因子涉及到的股票的分组(行业分类),日期为索引，股票品种为columns,默认为空|\n",
    "|period |否  |int|持有周期,默认为5,即持有5天|\n",
    "|n_quantiles |否  |int|根据每日因子值的大小分成n_quantiles组,默认为5,即将因子每天分成5组|\n",
    "|mask |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示在做因子分析时是否要对某期的某个品种过滤。对应位置为True则**过滤**（剔除）——不纳入因子分析考虑。默认为空，不执行过滤操作|\n",
    "|can_enter |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示某期的某个品种是否可以买入(进场)。对应位置为True则可以买入。默认为空，任何时间任何品种均可买入|\n",
    "|can_exit |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示某期的某个品种是否可以卖出(出场)。对应位置为True则可以卖出。默认为空，任何时间任何品种均可卖出|\n",
    "|forward |否  |bool|收益对齐方式,forward=True则在当期因子下对齐下一期实现的收益；forward=False则在当期实现收益下对齐上一期的因子值。默认为True|\n",
    "|commission |否 |float|手续费比例,每次换仓收取的手续费百分比,默认为万分之八0.0008|\n",
    "|ret_type |否 |string|计算何种收益的ic。目前支持的收益类型有return, upside_ret, downside_ret,分别代表固定调仓收益,潜在最大上涨收益,潜在最大下跌收益。默认为return--固定调仓收益|\n",
    "\n",
    "**返回:**\n",
    "\n",
    "ret_df 多个因子收益序列矩阵\n",
    "类型pd.Dataframe,索引（index）为datetime,columns为各因子名称，与factors_dict中的对应。\n",
    "如：\n",
    "\n",
    "```\n",
    "\n",
    "         BP\t　　　     CFP\t　　　EP\t　　ILLIQUIDITY\tREVS20\t　　SRMI\t　　　VOL20\n",
    "date\n",
    "2016-06-24\t0.165260\t0.002198\t0.085632\t-0.078074\t0.173832\t0.214377\t0.068445\n",
    "2016-06-27\t0.165537\t0.003583\t0.063299\t-0.048674\t0.180890\t0.202724\t0.081748\n",
    "2016-06-28\t0.135215\t0.010403\t0.059038\t-0.034879\t0.111691\t0.122554\t0.042489\n",
    "2016-06-29\t0.068774\t0.019848\t0.058476\t-0.049971\t0.042805\t0.053339\t0.079592\n",
    "2016-06-30\t0.039431\t0.012271\t0.037432\t-0.027272\t0.010902\t0.077293\t-0.050667\n",
    "```\n",
    "\n",
    "\n",
    "\n",
    "**示例：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>pb</th>\n",
       "      <th>pe</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>trade_date</th>\n",
       "      <th>group</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"5\" valign=\"top\">20170503</th>\n",
       "      <th>交通运输</th>\n",
       "      <td>-0.013851</td>\n",
       "      <td>-0.000394</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>休闲服务</th>\n",
       "      <td>-0.003584</td>\n",
       "      <td>-0.000479</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>传媒</th>\n",
       "      <td>0.009575</td>\n",
       "      <td>-0.003602</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>公用事业</th>\n",
       "      <td>-0.012407</td>\n",
       "      <td>-0.000983</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>农林牧渔</th>\n",
       "      <td>-0.029078</td>\n",
       "      <td>0.000052</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        pb        pe\n",
       "trade_date group                    \n",
       "20170503   交通运输  -0.013851 -0.000394\n",
       "           休闲服务  -0.003584 -0.000479\n",
       "           传媒     0.009575 -0.003602\n",
       "           公用事业  -0.012407 -0.000983\n",
       "           农林牧渔  -0.029078  0.000052"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from jaqs_fxdayu.research.signaldigger.multi_factor import get_factors_ret_df\n",
    "\n",
    "factor_ret_df = get_factors_ret_df(factors_dict,\n",
    "                                   price=dv.get_ts(\"close_adj\"),\n",
    "                                   high=dv.get_ts(\"high_adj\"), # 可为空\n",
    "                                   low=dv.get_ts(\"low_adj\"),# 可为空\n",
    "                                   group=dv.get_ts(\"sw1\"), # 可为空\n",
    "                                   quantiles=5,# quantile分类数\n",
    "                                   period=5,# 持有期\n",
    "                                   benchmark_price=dv.data_benchmark, # 基准价格 可不传入，持有期收益（return）计算为绝对收益\n",
    "                                   commission = 0.0008,\n",
    "                                   ret_type = 'downside_ret' # 计算最大潜在下跌收益的因子收益 \n",
    "                                 )\n",
    "factor_ret_df.dropna(how=\"all\").head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## combine_factors\n",
    "- ` jaqs_fxdayu.research.signaldigger.multi_factor.combine_factors(*args, **kwargs) `\n",
    "\n",
    "**简要描述：**\n",
    "\n",
    "-  多因子组合——最终合成一个组合因子\n",
    "\n",
    "**参数:**\n",
    "\n",
    "|字段|必选|类型|说明|\n",
    "|:----    |:---|:----- |-----   |\n",
    "|factors_dict|是|dict of pandas.DataFrame | 若干因子组成的字典(dict),形式为:{\"factor_name_1\":factor_1,\"factor_name_2\":factor_2}。每个因子值格式为一个pd.DataFrame，索引(index)为date,column为asset|\n",
    "|standardize_type|否|string| 标准化方法，有\"rank\"（排序标准化）,\"z_score\"(z-score标准化)两种（\"rank\"/\"z_score\"），默认为\"z_score\"|\n",
    "|winsorization|否|bool| 是否对结果执行去极值操作。默认不执行（False）|\n",
    "|index_member |否|pandas.DataFrame of bool |是否是指数成分股。日期为索引,证券品种为columns的二维bool值表格,True代表该品种在该日期下属于指数成分股。传入该参数,则在对结果进行标准化/去极值操作时所纳入的样本只有每期横截面上属于对应指数成分股的股票，默认为空|\n",
    "|weighted_method|否|string | 组合方式，目前支持'equal_weight'(等权合成),'ic_weight'(以某个时间窗口的滚动平均ic为权重), 'ir_weight'(以某个时间窗口的滚动ic_ir为权重), 'max_IR'(最大化上个持有期的ic_ir为目标处理权重)，'max_IC'(最大化上个持有期的ic为目标处理权重),'factors_ret_weight'(以某个时间窗口的滚动因子收益为权重)。默认采取'equal_weight'(等权合成)方式。若此处参数不为'equal_weight，则还需配置接下来的props参数|\n",
    "|props|weighted_method不等于'equal_weight'时必须,否则可以缺省|dict|计算加权合成因子时的必要配置信息。具体配置方式见下|\n",
    "\n",
    "**props配置参数**\n",
    "\n",
    "|字段|缺省值|类型|说明|\n",
    "|:----    |:---|:----- |-----   |\n",
    "|price |是，price与daily_ret二选一  |pandas.DataFrame|因子涉及到的股票的价格数据，用于作为进出场价用于计算收益,日期为索引，股票品种为columns|\n",
    "|daily_ret |是，price与daily_ret二选一  |pandas.DataFrame| 因子涉及到的股票的每日收益，日期为索引，股票品种为columns|\n",
    "|benchmark_price | 否，benchmark_price与daily_benchmark_ret二选一  |pandas.DataFrame or pandas.Series|基准价格，日期为索引。用于计算因子涉及到的股票的持有期**相对收益**--相对基准。默认为空，为空时计算的收益为**绝对收益**。|\n",
    "|daily_benchmark_ret | 否，benchmark_price与daily_benchmark_ret二选一  |pandas.DataFrame or pandas.Series|基准日收益，日期为索引。用于计算因子涉及到的股票的持有期**相对收益**--相对基准。默认为空，为空时计算的收益为**绝对收益**。|\n",
    "|high |否  |pandas.DataFrame|因子涉及到的股票的最高价数据,用于计算持有期潜在最大上涨收益,日期为索引，股票品种为columns,默认为空|\n",
    "|low |否  |pandas.DataFrame|因子涉及到的股票的最低价数据,用于计算持有期潜在最大下跌收益,日期为索引，股票品种为columns,默认为空|\n",
    "|ret_type |否 |string|计算何种收益的ic。目前支持的收益类型有return, upside_ret, downside_ret,分别代表固定调仓收益,潜在最大上涨收益,潜在最大下跌收益。默认为return--固定调仓收益|\n",
    "|period |否  |int|持有周期,默认为5,即持有5天|\n",
    "|n_quantiles |否  |int|根据每日因子值的大小分成n_quantiles组,默认为5,即将因子每天分成5组|\n",
    "|mask |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示在做因子分析时是否要对某期的某个品种过滤。对应位置为True则**过滤**（剔除）——不纳入因子分析考虑。默认为空，不执行过滤操作|\n",
    "|can_enter |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示某期的某个品种是否可以买入(进场)。对应位置为True则可以买入。默认为空，任何时间任何品种均可买入|\n",
    "|can_exit |否  |pandas.DataFrame|一张由bool值组成的表格,日期为索引，股票品种为columns，表示某期的某个品种是否可以卖出(出场)。对应位置为True则可以卖出。默认为空，任何时间任何品种均可卖出|\n",
    "|forward |否  |bool|收益对齐方式,forward=True则在当期因子下对齐下一期实现的收益；forward=False则在当期实现收益下对齐上一期的因子值。默认为True|\n",
    "|commission |否 |float|手续费比例,每次换仓收取的手续费百分比,默认为万分之八0.0008|\n",
    "|covariance_type |否 |string|估算协方差矩阵的方法。有'simple'（普通协方差矩阵估算），'shrink'（压缩协方差矩阵估算）两种。默认为'simple'|\n",
    "|rollback_period |否 |int| 滚动窗口天数。默认为120天|\n",
    "\n",
    "**返回:**\n",
    "\n",
    "合成后的新因子\n",
    "\n",
    "**示例：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Nan Data Count (should be zero) : 0;  Percentage of effective data: 99%\n",
      "Nan Data Count (should be zero) : 0;  Percentage of effective data: 99%\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th>symbol</th>\n",
       "      <th>000001.SZ</th>\n",
       "      <th>000002.SZ</th>\n",
       "      <th>000008.SZ</th>\n",
       "      <th>000009.SZ</th>\n",
       "      <th>000027.SZ</th>\n",
       "      <th>000039.SZ</th>\n",
       "      <th>000060.SZ</th>\n",
       "      <th>000061.SZ</th>\n",
       "      <th>000063.SZ</th>\n",
       "      <th>000069.SZ</th>\n",
       "      <th>...</th>\n",
       "      <th>601988.SH</th>\n",
       "      <th>601989.SH</th>\n",
       "      <th>601992.SH</th>\n",
       "      <th>601997.SH</th>\n",
       "      <th>601998.SH</th>\n",
       "      <th>603000.SH</th>\n",
       "      <th>603160.SH</th>\n",
       "      <th>603858.SH</th>\n",
       "      <th>603885.SH</th>\n",
       "      <th>603993.SH</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>trade_date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>20170726</th>\n",
       "      <td>1.777932</td>\n",
       "      <td>0.919536</td>\n",
       "      <td>-0.807974</td>\n",
       "      <td>-1.249868</td>\n",
       "      <td>1.221546</td>\n",
       "      <td>-0.453661</td>\n",
       "      <td>-1.012164</td>\n",
       "      <td>-1.202203</td>\n",
       "      <td>0.745612</td>\n",
       "      <td>1.294838</td>\n",
       "      <td>...</td>\n",
       "      <td>1.873679</td>\n",
       "      <td>-0.606958</td>\n",
       "      <td>0.822860</td>\n",
       "      <td>1.363824</td>\n",
       "      <td>1.819174</td>\n",
       "      <td>-1.559370</td>\n",
       "      <td>-1.496059</td>\n",
       "      <td>-0.308391</td>\n",
       "      <td>0.110494</td>\n",
       "      <td>-1.406211</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170727</th>\n",
       "      <td>1.789675</td>\n",
       "      <td>0.921333</td>\n",
       "      <td>-0.770788</td>\n",
       "      <td>-1.240962</td>\n",
       "      <td>1.232906</td>\n",
       "      <td>-0.427585</td>\n",
       "      <td>-0.931221</td>\n",
       "      <td>-1.178000</td>\n",
       "      <td>1.022124</td>\n",
       "      <td>1.274817</td>\n",
       "      <td>...</td>\n",
       "      <td>1.873890</td>\n",
       "      <td>-0.579308</td>\n",
       "      <td>0.817697</td>\n",
       "      <td>1.354356</td>\n",
       "      <td>1.825470</td>\n",
       "      <td>-1.581904</td>\n",
       "      <td>-1.512148</td>\n",
       "      <td>-0.348058</td>\n",
       "      <td>0.081561</td>\n",
       "      <td>-1.364542</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170728</th>\n",
       "      <td>1.781449</td>\n",
       "      <td>0.853104</td>\n",
       "      <td>-0.752057</td>\n",
       "      <td>-1.257739</td>\n",
       "      <td>1.260455</td>\n",
       "      <td>-0.383558</td>\n",
       "      <td>-0.931522</td>\n",
       "      <td>-1.159573</td>\n",
       "      <td>0.933568</td>\n",
       "      <td>1.250720</td>\n",
       "      <td>...</td>\n",
       "      <td>1.877950</td>\n",
       "      <td>-0.520732</td>\n",
       "      <td>0.858098</td>\n",
       "      <td>1.352325</td>\n",
       "      <td>1.823944</td>\n",
       "      <td>-1.560053</td>\n",
       "      <td>-1.525730</td>\n",
       "      <td>-0.373445</td>\n",
       "      <td>0.057556</td>\n",
       "      <td>-1.363146</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170731</th>\n",
       "      <td>1.787901</td>\n",
       "      <td>0.855996</td>\n",
       "      <td>-0.738105</td>\n",
       "      <td>-1.280330</td>\n",
       "      <td>1.280363</td>\n",
       "      <td>-0.356675</td>\n",
       "      <td>-0.958028</td>\n",
       "      <td>-1.126765</td>\n",
       "      <td>0.909647</td>\n",
       "      <td>1.247865</td>\n",
       "      <td>...</td>\n",
       "      <td>1.871937</td>\n",
       "      <td>-0.441376</td>\n",
       "      <td>0.885835</td>\n",
       "      <td>1.361503</td>\n",
       "      <td>1.831151</td>\n",
       "      <td>-1.541315</td>\n",
       "      <td>-1.548003</td>\n",
       "      <td>-0.392538</td>\n",
       "      <td>0.040312</td>\n",
       "      <td>-1.348098</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20170801</th>\n",
       "      <td>1.773030</td>\n",
       "      <td>0.840944</td>\n",
       "      <td>-0.737895</td>\n",
       "      <td>-1.237729</td>\n",
       "      <td>1.312784</td>\n",
       "      <td>-0.297223</td>\n",
       "      <td>-0.869217</td>\n",
       "      <td>-1.074826</td>\n",
       "      <td>0.883651</td>\n",
       "      <td>1.237696</td>\n",
       "      <td>...</td>\n",
       "      <td>1.875752</td>\n",
       "      <td>-0.397516</td>\n",
       "      <td>0.756331</td>\n",
       "      <td>1.344476</td>\n",
       "      <td>1.829015</td>\n",
       "      <td>-1.527066</td>\n",
       "      <td>-1.554451</td>\n",
       "      <td>-0.398535</td>\n",
       "      <td>0.025989</td>\n",
       "      <td>-1.326178</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>5 rows × 330 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "symbol      000001.SZ  000002.SZ  000008.SZ  000009.SZ  000027.SZ  000039.SZ  \\\n",
       "trade_date                                                                     \n",
       "20170726     1.777932   0.919536  -0.807974  -1.249868   1.221546  -0.453661   \n",
       "20170727     1.789675   0.921333  -0.770788  -1.240962   1.232906  -0.427585   \n",
       "20170728     1.781449   0.853104  -0.752057  -1.257739   1.260455  -0.383558   \n",
       "20170731     1.787901   0.855996  -0.738105  -1.280330   1.280363  -0.356675   \n",
       "20170801     1.773030   0.840944  -0.737895  -1.237729   1.312784  -0.297223   \n",
       "\n",
       "symbol      000060.SZ  000061.SZ  000063.SZ  000069.SZ    ...      601988.SH  \\\n",
       "trade_date                                                ...                  \n",
       "20170726    -1.012164  -1.202203   0.745612   1.294838    ...       1.873679   \n",
       "20170727    -0.931221  -1.178000   1.022124   1.274817    ...       1.873890   \n",
       "20170728    -0.931522  -1.159573   0.933568   1.250720    ...       1.877950   \n",
       "20170731    -0.958028  -1.126765   0.909647   1.247865    ...       1.871937   \n",
       "20170801    -0.869217  -1.074826   0.883651   1.237696    ...       1.875752   \n",
       "\n",
       "symbol      601989.SH  601992.SH  601997.SH  601998.SH  603000.SH  603160.SH  \\\n",
       "trade_date                                                                     \n",
       "20170726    -0.606958   0.822860   1.363824   1.819174  -1.559370  -1.496059   \n",
       "20170727    -0.579308   0.817697   1.354356   1.825470  -1.581904  -1.512148   \n",
       "20170728    -0.520732   0.858098   1.352325   1.823944  -1.560053  -1.525730   \n",
       "20170731    -0.441376   0.885835   1.361503   1.831151  -1.541315  -1.548003   \n",
       "20170801    -0.397516   0.756331   1.344476   1.829015  -1.527066  -1.554451   \n",
       "\n",
       "symbol      603858.SH  603885.SH  603993.SH  \n",
       "trade_date                                   \n",
       "20170726    -0.308391   0.110494  -1.406211  \n",
       "20170727    -0.348058   0.081561  -1.364542  \n",
       "20170728    -0.373445   0.057556  -1.363146  \n",
       "20170731    -0.392538   0.040312  -1.348098  \n",
       "20170801    -0.398535   0.025989  -1.326178  \n",
       "\n",
       "[5 rows x 330 columns]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from jaqs_fxdayu.research.signaldigger.multi_factor import combine_factors\n",
    "\n",
    "props = {\n",
    "    'price':dv.get_ts(\"close_adj\"),\n",
    "    'high':dv.get_ts(\"high_adj\"), # 可为空\n",
    "    'low':dv.get_ts(\"low_adj\"),# 可为空\n",
    "    'ret_type': 'return',#可选参数还有upside_ret/downside_ret 则组合因子将以优化潜在上行、下行空间为目标\n",
    "    'daily_benchmark_ret': dv.data_benchmark.pct_change(1),  # 为空计算的是绝对收益　不为空计算相对收益\n",
    "    'period': 30, # 30天的持有期\n",
    "    'forward': True,\n",
    "    'commission': 0.0008,\n",
    "    \"covariance_type\": \"shrink\",  # 协方差矩阵估算方法 还可以为\"simple\"\n",
    "    \"rollback_period\": 30}  # 滚动窗口天数\n",
    "\n",
    "comb_factor = combine_factors(factors_dict,\n",
    "                              standardize_type=\"z_score\",\n",
    "                              winsorization=False,\n",
    "                              weighted_method=\"ic_weight\",\n",
    "                              props=props)\n",
    "    \n",
    "\n",
    "comb_factor.dropna(how=\"all\").head()"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [conda env:IIA]",
   "language": "python",
   "name": "conda-env-IIA-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
